<template>
  <div class="sidebar-item-wrapper">
    <!-- 当存在子路由且子路由需要显示在菜单中时，使用el-submenu -->
    <el-submenu v-if="hasChildren(item)" :index="resolvePath(item.path)">
      <template slot="title">
        <i v-if="item.meta && item.meta.icon" :class="item.meta.icon"></i>
        <span v-if="item.meta && item.meta.title">{{ item.meta.title }}</span>
      </template>
      
      <!-- 递归渲染子菜单 -->
      <sidebar-item
        v-for="child in item.children"
        :key="child.path"
        :item="child"
        :base-path="resolvePath(child.path)"
      />
    </el-submenu>
    
    <!-- 当没有子路由或子路由不需要显示在菜单中时，使用el-menu-item -->
    <el-menu-item v-else :index="resolvePath(item.path)">
      <i v-if="item.meta && item.meta.icon" :class="item.meta.icon"></i>
      <span slot="title" v-if="item.meta && item.meta.title">{{ item.meta.title }}</span>
    </el-menu-item>
  </div>
</template>

<script>
import path from 'path'

export default {
  name: 'SidebarItem',
  props: {
    item: {
      type: Object,
      required: true
    },
    basePath: {
      type: String,
      default: ''
    }
  },
  methods: {
    // 检查是否有需要在菜单中显示的子路由
    hasChildren(item) {
      if (item.children && item.children.length > 0) {
        const showingChildren = item.children.filter(child => {
          return !child.meta || !child.meta.hidden
        })
        return showingChildren.length > 0
      }
      return false
    },
    
    // 解析路由路径
    resolvePath(routePath) {
      if (this.isExternal(routePath)) {
        return routePath
      }
      if (this.isExternal(this.basePath)) {
        return this.basePath
      }
      return path.resolve(this.basePath, routePath)
    },
    
    // 检查是否是外部链接
    isExternal(path) {
      return /^(https?:|mailto:|tel:)/.test(path)
    }
  }
}
</script>

<style lang="scss" scoped>
.sidebar-item-wrapper {
  .el-menu-item, .el-submenu__title {
    height: 50px;
    line-height: 50px;
    
    i {
      margin-right: 10px;
    }
  }
}
</style> 